angular.module('Caltech')
.controller('equipmentItemController', function ($scope, Restangular, $stateParams, $q, moment, $state, Constants, toaster) {
    'use strict';
    $scope.username = Constants.accountInfo.fullName;
    if ($stateParams.id) {
	    Restangular.one('equipment', $stateParams.id).get().then(function (data) {
	        $scope.model = data;
	        $scope.isValid = true;
		});
	} else {
	    $scope.model = {	       
	        calibrationDate: new Date(),
	        nextDueDate: moment().add('years', 1).toDate()
	    };
    }

    if ($stateParams.model) {
        // it's copy mode
        $scope.model = JSON.parse($stateParams.model);
    }

	$scope.update = function (model) {
        return model.put().then(function () {
            $state.forceReload();
        });
    };

	$scope.save = function (model) {
	    return Restangular.all('equipment').post(model).then(function (id) {
	        $state.go('equipment-item', { id: id });
	    });
	};
	
	$scope.copy = function () {
	    var model = Restangular.stripRestangular($scope.model);

	    toaster.pop('info', "Info", 'Prepared a copy version of equipment. ' + model.id);

	    model.id = undefined;
	    $state.go('equipment-new', {
	        model: JSON.stringify(model)
	    });
	};

    $scope.remove = function (model) {
        return model.remove().then(function () {
            history.back();
        });
    };


    $scope.validate = function (model, manufacturer) {
        if (model && manufacturer) {
            return Restangular.all('equipment').customGET(
                    'validate',
                    { model: model, manufacturer: manufacturer, id: $scope.model.id }).then(function (response) {
                        $scope.isValid = response.result;

                        if (!response.result) {
                            return $q.reject('Duplicated Manufacturer + Model # is not allowed');
                        }
                    });
        }
    };
});